package com.ws.exer;

import sun.awt.windows.WPrinterJob;

import java.util.Arrays;

/*
4.对象数组题目
对 StudentTest 的优化

 */
public class StudentTest2 {
    public static void main(String[] args) {

        //声明一个student数组
        Student2[] students2 = new Student2[20];

        for (int i = 0; i < students2.length; i++) {
            //给数组元素赋值
            students2[i] = new Student2();
            //给Student对象的属性赋值
            students2[i].number = i + 1;
            //年级：[1, 6]
            students2[i].state = (int) (Math.random() * 6 + 1);
            //成绩：[0, 100]
            students2[i].score = (int) (Math.random() * 101);
        }


        StudentTest2 studentTest2 = new StudentTest2();

        //遍历Student2[]数组的操作
        studentTest2.print(students2);//遍历Student数组
        System.out.println("************************");

        //问题一:打印出3年级( state值为3）的学生信息。
        studentTest2.findByState(students2, 3);//查找那个年级的
        System.out.println("***********************");

        //问题二:使用冒泡排序按学生成绩排序，并遍历所有学生信息
        studentTest2.sortByScore(students2);//按分数排序
        studentTest2.print(students2);
    }


    public void print(Student2[] students2) {
        for (Student2 student2 : students2) {
            System.out.println(student2.info());
        }
    }


    public void findByState(Student2[] students2, int state) {
        for (Student2 student : students2) {
            if (student.state == state) {
                System.out.println(student.info());
            }
        }
    }


    public void sortByScore(Student2[] students2) {
        for (int i = 0; i < students2.length - 1; i++) {
            for (int j = 0; j < students2.length - i - 1; j++) {
                if (students2[j].score > students2[j+1].score) {
                    //如果需要换序，交换的是数组的元素：Student对象
                    Student2 temp = students2[j];
                    students2[j] = students2[j+1];
                    students2[j+1] = temp;
                }
            }
        }
    }

}

class Student2 {
    int number;//学号
    int state;//年级
    int score;//成绩

    //显示学生信息的方法
    public String info() {
        return "学号：" + number + "，年级：" + state + "，成绩：" + score;
    }


}
